<?php
namespace app\home\controller;
use app\index\controller\Basics;
use think\facade\Db;
use think\facade\Session;
use think\response\Json;


/*
 * 房间界面
 *
 * */

class Welcome extends Basics
{


    /*
     * 显示房态图
     *
     * */
    public function index()
    {
        if(request()->isAjax()){
            $list =  Db::table('room')
                ->alias('a')
                ->field('a.*,b.type_name,b.price,b.deposit,b.hour,c.building,d.storey,e.monday')
                ->join('layout b','a.type_id = b.id')
                ->join('building c','a.building_id = c.id')
                ->join('storey d','a.storey_id = d.id')
                ->join('week e','a.id = e.layout_id')
                ->where('a.id',input('id'))
                ->find();
            return \json($list);
        }

        if(request()->Get()){

            $data = input('param.');
            if(!empty($data)){

                if(!empty($data['status']) && $data['status'] !=0){
                    \session('statuss',$data['status']);
                    $map = [
                        ['a.building_id','=',session('building_id')],
                        ['a.status','=',$data['status']],
                    ];
                }else{
                    \session('statuss','all');
                    $map = [
                        ['a.building_id','=',session('building_id')]
                    ];
                }
                if (!empty($data['room_num'])){
                    $room_num = '%'.$data['room_num'].'%';
                    $map = [
                        ['a.building_id','=',session('building_id')],
                        ['a.room_num','like',$room_num],
                    ];
                }
                if (!empty($data['type_id']) && $data['type_id'] != 'all'){
                    \session('type_id',$data['type_id']);
                    $map = [
                        ['a.building_id','=',session('building_id')],
                        ['a.type_id','=',$data['type_id']],
                    ];
                }else{
                    \session('type_id','all');
                }
            }
        }else{
            $map = [
                ['a.building_id','=',session('building_id')]
            ];
        }

        $list =  Db::table('room')
            ->alias('a')
            ->field('a.*,b.type_name,b.price,b.deposit,b.hour,c.building,d.storey,e.monday')
            ->join('layout b','a.type_id = b.id')
            ->join('building c','a.building_id = c.id')
            ->join('storey d','a.storey_id = d.id')
            ->join('week e','a.id = e.layout_id')
            ->where($map)
            ->order('a.status', 'desc')
            ->paginate(['list_rows'=> 20,'query' => input('param.')]);

        $layout = $this->select_all('layout');
        return view('index',['list'=>$list,'layout'=>$layout]);
    }
    /*
     * 入住界面
     * */
    public function move()
    {
        if(request()->isPost())
        {
            $datas = input('param.');

            //检测用户是否在黑名单
            $blacklist = Db::table('blacklist')->where('name',$datas['guest_name'])->find();
            if(!empty($blacklist)){
                if($blacklist['identity']  == $datas['credentials']){
                    return "<script>alert('黑名单用户!');location.href='".$_SERVER["HTTP_REFERER"]."';</script>";
                }
            }

            if(!empty($datas['hours'])){
                $datas['in_time'] = date('Y-m-dH-m-s',time());
                $datas['move_time'] = date('Y-m-dH-m-s',time()+$datas['hours'] * 3600);
            }
            $data['guest_name'] = $datas['guest_name'];
            $data['activity_id'] = $datas['activity_id'];
            $data['credentials'] = $datas['credentials'];
            $data['guest_tel'] = $datas['guest_tel'];
/*            $data['in_time'] = $datas['in_time'];
            $data['move_time'] = $datas['move_time'];*/
            $data['in_time'] = str_replace('-','',$datas['in_time']);
            $data['move_time'] = str_replace('-','',$datas['move_time']);
            $data['guest_sex'] = $datas['guest_sex'];
            $data['guest_source'] = $datas['guest_source'];
            $data['member_id'] = $datas['member_id'];
            $data['status'] = '2';
            $data['room_id'] = 'no';

            //主房间添加
            if(Db::table('room')->where('id',$datas['id'])->update($data)){
                $user['user_name'] = $datas['guest_name'];
                $user['user_num'] = $datas['credentials'];
                $user['room_id'] = $datas['room_num'];
                $user['create_time']=time();
                Db::table('hotel_move_ren')->insert($user);
                //保存价格数据
                if(empty($datas['room_arr']) || strpos($datas['room_arr'],',') == false ){
                    $this->record($datas);
                    return redirect('/home/welcome/detailed/room_id/'.$datas['id'].'');
                }

            }else{
                Session::flash('msg','入住失败');
            }
            //添加的更多房间的入住人
            if(!empty($datas['room_arr'])){
                //多房间多人入住
                if(strpos($datas['room_arr'],',') !== false ){
                    $arr = explode(",", $datas['room_arr']);

                    $user['user_name'] = $datas['user_name'];
                    $user['user_num'] = $datas['user_num'];
                    $user['room_id'] = $datas['room_id'];
                    //多房间多人入住添加数据
                    foreach ($user['user_name'] as $k=>$v){
                        $user_name = $user['user_name'][$k]; //姓名
                        $user_num = $user['user_num'][$k]; //身份证
                        $room_id = $user['room_id'][$k]; //房间id
                        $data = [
                            'user_name'=>$user_name,
                            'user_num'=>$user_num,
                            'room_id'=>$room_id,
                            'create_time'=>time(),
                        ];

                        Db::table('hotel_move_ren')->insert($data);
                    }
                    //将第一个入住人加入room表中
                    for ($x=0; $x < count($arr); $x++) {
                        $map = [
                            ['room_id','=',$arr[$x]],
                            ['status','=','1']
                        ];
                        $res = Db::table('room')->where('id',$datas['id'])->find();
                        if($arr[$x] != $res['room_num']){
                            $list = Db::table('hotel_move_ren')->where($map)->find();
                            Db::table('room')->where('room_num',$arr[$x])
                                ->update([
                                    'guest_name'=>$list['user_name'],
                                    'credentials'=>$list['user_num'],
                                    'status'=>'2',
                                    'room_id' => $datas['id'],
                                    'in_time'=>str_replace('-','',$datas['in_time']),
                                    'move_time'=>str_replace('-','',$datas['move_time'])
                                ]);
                        }
                    }
                    //保存价格数据
                    $this->record($datas);
                    return redirect('/home/welcome/detailed/room_id/'.$datas['room_arr'].'/id/'.$datas['room_num'].'');
                }else{
                    //只能主房间添加多人的时候走这里
                    $user['user_name'] = $datas['user_name'];
                    $user['user_num'] = $datas['user_num'];
                    //添加入住信息
                    foreach ($user['user_name'] as $k=>$v){
                        $user_name = $user['user_name'][$k]; //姓名
                        $user_num = $user['user_num'][$k]; //身份证
                        Db::table('hotel_move_ren')->insert([
                            'room_id'=>$datas['room_num'],
                            'user_name'=>$user_name,
                            'user_num'=>$user_num,
                            'create_time'=>time(),
                        ]);
                    }
                }
            }
        }
        //查询可追加的房间--------------------------------------
        $id = input('id');
        $map = [
            ['a.building_id','=',session('building_id')],
            ['a.room_id','=','no'],
            ['a.id','<>',$id],
            ['a.status','=','1'],
        ];
        $list =  Db::table('room')
            ->alias('a')
            ->field('a.*,b.type_name,b.price,b.deposit,c.building,d.storey')
            ->join('layout b','a.type_id = b.id')
            ->join('building c','a.building_id = c.id')
            ->join('storey d','a.storey_id = d.id')
            ->where($map)
            ->select();
        $activity = Db::table('Activitys')->where('building_id',session('building_id'))->select();//促销活动
        $guest = $this->select_all('guest');//宾客来源
        $payment = $this->select_all('payment');//支付方式
        $room = Db::table('room')->where('id',$id)->find();
        $member = Db::name('member')->where(['building_id'=>session('building_id')])->paginate('10');
        return view('move',['list'=>$list,'id'=>$id,'room'=>$room['room_num'],'activity' => $activity,'guest' => $guest,'payment' => $payment,'member'=>$member]);
    }

    /*
     * 入住房间价格和记录收入信息
     * */
    public function record($data)
    {
        //查询优惠活动
        if(empty($data['activity_id'])){
            $datas['activity_price'] = '1';
        }else{
            $list = $this->select_find('activitys',['id' => $data['activity_id']]);
            if(strtotime($list['start']) <= time() && strtotime($list['end']) <= time() ){
                $datas['activity_price'] = $list['price'];
            }else{
                $datas['activity_price'] = '1';
            }
        }

        //会员折扣
        if(isset($data['member_id']) && $data['member_id'] != 0){
            $member =  Db::table('member')
                ->alias('a')
                ->field('a.*,b.price')
                ->join('viptype b','a.type = b.id')
                ->where(['a.id' => $data['member_id']])
                ->find();
            $datas['member_price'] = $member['price'];
        }else{
            $datas['member_price'] = '1';
        }
        //判断客户需要入住几天
        if(empty($data['hours'])){
//            $times= str_replace('-','',$data['move_time']) - str_replace('-','',$data['in_time']);
            $times = $this->diffBetweenTwoDays($data['in_time'],$data['move_time']);
            if(!$times){
                $times = '1';
            }
        }

        if(strpos($data['room_arr'],',') !== false ){
            $arr = explode(",", $data['room_arr']);
            //判断主房间的房间号是否存在，不存在就追加到数组中
            $arrays = $this->select_find('room',['id' => $data['id']]);
            if(!in_array($arrays['room_num'], $arr)){
                array_push($arr,$arrays['room_num']);
            }
            //循环数组添加数据
            for ($x=0; $x < count($arr); $x++) {
                //根据房间号找房间的id
                $res =  Db::table('room')
                    ->alias('a')
                    ->field('a.*,b.type_name,b.price,b.deposit,b.hour,c.monday')
                    ->join('layout b','a.type_id = b.id')
                    ->join('week c','a.id = c.layout_id')
                    ->where('a.room_num',$arr[$x])
                    ->find();
                //判断是不是按小时计费
                if(!empty($data['hours'])){
                    $datas['income_details'] = $res['hour'] * $data['hours'];
                    $datas['types'] = '2';
                }else{
                    $datas['income_details'] = $res['monday'] * $times;
                }

                $datas['room_id'] = $res['id'];
                //查询押金
/*                $show =  Db::table('room')
                    ->alias('a')
                    ->field('a.*,b.type_name,b.price,b.deposit')
                    ->join('layout b','a.type_id = b.id')
                    ->where(['a.id' => $res['id']])
                    ->find();
                $datas['deposit_record'] = $show['deposit'] ;*/
                $datas['deposit_record'] = '0' ;
                $datas['create_time'] = time();

                Db::name('income')->save($datas);
            }
        }else{
//            $list = $this->select_find('week',['layout_id' => $data['id']]);
            $list =  Db::table('room')
                ->alias('a')
                ->field('a.*,b.type_name,b.price,b.deposit,b.hour,c.monday')
                ->join('layout b','a.type_id = b.id')
                ->join('week c','a.id = c.layout_id')
                ->where('c.layout_id',$data['id'])
                ->find();
            //判断是不是按小时计费
            if(!empty($data['hours'])){
                $datas['income_details'] = $list['hour'] * $data['hours'];
                $datas['types'] = '2';
            }else{
                $datas['income_details'] = $list['monday'] * $times;
            }

            $datas['room_id'] = $data['id'];
            //查询押金
/*            $show =  Db::table('room')
                ->alias('a')
                ->field('a.*,b.type_name,b.price,b.deposit')
                ->join('layout b','a.type_id = b.id')
                ->where(['a.id' => $data['id']])
                ->find();
            $datas['deposit_record'] = $show['deposit'] ;*/
            $datas['deposit_record'] = '0' ;
            $datas['create_time'] = time();

            Db::name('income')->save($datas);
        }
    }

    /*
     * 会员选择
     * */
    public function select_member(){
        $data = $this->select_find('member',['id' => input('id')]);
        return json($data);
    }

    /*
     * 查询更多入住人员
     * */
    public function more_personnel(){
        $map = [
            ['room_id','=',input('room_num')],
            ['status','=','1']
        ];
        $list = Db::table('hotel_move_ren')->where($map)->select();
        return view('more_personnel',['list'=>$list]);
    }

    /*
     * 显示价格明细
     * */

    public function detailed(){

        $data = input('param.');
        //多住户
        if(strpos($data['room_id'],',') !== false ){
            $arr = explode(",", $data['room_id']);
            array_push($arr,$data['id']);
            $room_arr = implode(",", $arr);
            $res['count'] = count($arr);
            $ids = [];
            foreach ($arr as $v){
                $show =  Db::table('room')
                    ->where(['room_num' => $v])
                    ->find();
                array_push($ids,$show['id']);
            }
            $res['income_details'] = [];
            $res['deposit_record'] = [];
            foreach ($ids as $vs){

                $list = Db::table('income')
                    ->where(['room_id'=>$vs,'status'=>'1'])
                    ->find();

                 array_push($res['income_details'],$list['income_details']);
                 array_push($res['deposit_record'],$list['deposit_record']);
                $res['activity_price'] = $list['activity_price'];
                $res['member_price'] = $list['member_price'];
            }
                $res['income_details'] = array_sum($res['income_details']);
//                $res['deposit_record'] = array_sum($res['deposit_record']);
                $res['deposit_record'] = '0';
                $res['create_time'] = time();
                $res['room_arr'] = [];
                $list = Db::table('room')->where('room_num','IN',$room_arr)->select();

                foreach ($list as $v){
                    array_push($res['room_arr'],$v['id']);
                }
                $res['room_arr'] = implode(",", $res['room_arr']);
                $res['in_time'] = $list[0]['in_time'];
                $res['move_time'] = $list[0]['move_time'];
                $res['building_id'] = session('building_id');
                $res['price_receivable'] = $res['income_details'] * $res['member_price'] * $res['activity_price'] +$res['deposit_record'];
                $parent_id = Db::table('room')->where('room_num',$data['id'])->find();
                $res['parent_id'] = $parent_id['id'];
                $res['operator'] = session('admin_id');
                dump($res);
            //加入价格记录中
            if(!Db::table('home_room_income')->where(['room_arr'=>$res['room_arr'],'status'=>'1'])->find()){
                Db::table('home_room_income')->insert($res);
            }
        }else{
            //单住户
            $list = Db::table('income')
                    ->where(['room_id'=>$data['room_id'],'status'=>'1'])
                    ->find();
            $res['income_details'] = $list['income_details'];
//            $res['deposit_record'] = $list['deposit_record'];
            $res['deposit_record'] = '0';
            $res['create_time'] = time();
            $res['activity_price'] = $list['activity_price'];
            $res['member_price'] = $list['member_price'];
            $res['count'] = '1';
            $res['room_arr'] = $data['room_id'];
            $room_num = Db::table('room')->where('id',$data['room_id'])->find();
            $room_arr = $room_num['room_num'];
            $res['price_receivable'] = $res['income_details'] * $res['member_price'] * $res['activity_price'] +$res['deposit_record'];
            $res['in_time'] = $room_num['in_time'];
            $res['move_time'] = $room_num['move_time'];
            $res['building_id'] = session('building_id');
            $res['parent_id'] = $data['room_id'];
            $res['operator'] = session('admin_id');
            //加入价格记录中
            if(!Db::table('home_room_income')->where(['room_arr'=>$res['room_arr'],'status'=>'1'])->find()){
                Db::table('home_room_income')->insert($res);
            }
        }
        return view('detailed',['list'=>$res,'room_arr'=>$room_arr]);
    }

    /*
     * 取消入住订单
     * */
    public function cancel_order()
    {
        $data = input('room_arr');
        $list = Db::table('room')->where('room_num','IN',$data)->select();
        $datas = [
            'status' => 1,
            'room_id' => 'no',
            'guest_name' => '',
            'activity_id' => '',
            'credentials' => '',
            'guest_sex' =>'',
            'guest_source' =>'',
            'guest_number' =>'',
            'move_duration' =>'',
            'move_time' => '',
            'in_time' => ''
        ];
        if(strpos($data,',') !== false )
        {
            $room_id = [];
            foreach ($list as $v){
               array_push($room_id,$v['id']);
            }
            $room_id = implode(",", $room_id);
            if(Db::table('room')->where('id','IN',$room_id)->update($datas)){
                if( Db::table('income')->where('room_id','IN',$room_id)->delete()){
                    if(Db::table('hotel_move_ren')->where('room_id','IN',$data)->delete()){
                        Db::table('home_room_income')->where('room_arr',$room_id)->delete();
                        return $this->return_json('取消成功','100');
                    }else{
                        return $this->return_json('取消入住用户失败','0');
                    }
                }else{
                    return $this->return_json('取消记录失败','0');
                }
            }else{
                return $this->return_json('房间重置失败','0');
            }
        }else{
            $ress = Db::table('room')->where('room_num',$data)->find();

            $room_id = $ress['id'];

            if(Db::table('room')->where('id',$room_id)->update($datas)){
                if( Db::table('income')->where('room_id',$room_id)->delete()){
                    $room  = Db::table('room')->where('id',$room_id)->find();
                    if(Db::table('hotel_move_ren')->where('room_id',$room['room_num'])->delete()){
                        Db::table('home_room_income')->where('room_arr',$room_id)->delete();
                        return $this->return_json('取消成功','100');
                    }else{
                        return $this->return_json('取消入住用户失败','0');
                    }
                }else{
                    return $this->return_json('取消记录失败','0');
                }
            }else{
                return $this->return_json('房间重置失败','0');
            }
        }



    }

}
